import {
  Button, Form, Input, message, Modal, Select,
} from 'antd'
import React, { PureComponent } from 'react'
// import {
//   addUser, editUser, getRoleList, getlistUserSecret,
// } from './api'
import {
  getRoleList
} from './api'
import JSEncrypt from '@/utils/JSEncrypt.js'
import { regExp } from '@/utils/regExp'
import Tools from '@/utils/Tools'

const { Item } = Form
const { Option } = Select
const Bus = Tools.Bus

export default class AccountModal extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      // loading: false,
      visible: false,
      roleOptions: [],
      id: '',
      loading: false,
      listUserSecret: [],
    }

    this.form = React.createRef()
  }

  componentDidMount() {
    this.getRoleList()
    // this.getlistUserSecretFn()
  }

  // getlistUserSecretFn = () => {
  //   getlistUserSecret().then((res) => {
  //     this.setState({
  //       listUserSecret: res,
  //     })
  //   })
  // }

  // 获取角色列表
  getRoleList = () => {
    getRoleList().then(
      (res) => {
        const arr = []
        if (res && res.result) {
          res.result.map((item) => {
            arr.push({
              value: item.id,
              title: item.roleName,
            })
          })
        }
        this.setState({ roleOptions: arr })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  // 为表单赋值
  // eslint-disable-next-line react/no-unused-class-component-methods
  setValue(data) {
    const {
      displayName, id, phoneNumber, email,
    } = data
    const obj = {
      name: (displayName && displayName !== '') ? displayName : '--',
      id,
      phone: (phoneNumber && phoneNumber !== '') ? phoneNumber : '--',
      email: (email && email !== '') ? email : '--',
      // roleId,
      // dept: (dept && dept !== '') ? dept : '--',
      // title: (title && title !== '') ? title : '--',
      // rowState: rowState === 1 ? '是' : '否',
      // securityLevelId: securityLevelId || '',
    }
    this.form.current && this.form.current.setFieldsValue(obj)
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  openModal = () => {
    this.form.current && this.form.current.resetFields()
    this.setState({ visible: true })
  }

  closeModal = () => {
    this.setState({ visible: false })
  }

  // onConfirm = () => {
  //   this.form.current.validateFields().then(values => {
  //     this.setState({ loading: true })
  //     const { isEdit } = this.props
  //     if (isEdit) {
  //       const { password, ...other } = values
  //       const postObj = {
  //         ...other,
  //       }
  //       postObj.id = this.state.id
  //       // values.password = JSEncrypt(values.password)
  //       editUser(postObj).then(
  //         (res) => {
  //           this.setState({
  //             visible: false,
  //             loading: false,
  //           }, () => {
  //             message.success('编辑用户成功')
  //             this.props.closeCallBack && this.props.closeCallBack()
  //             // 刷新全局dva内保存的关于权限的信息
  //             Bus.emit('UpdateAuth')
  //           })
  //         },
  //         (error) => {
  //           console.log(error)
  //           this.setState({ loading: false })
  //         },
  //       )
  //     } else {
  //       values.password = JSEncrypt(values.password)
  //       addUser(values).then(
  //         (res) => {
  //           this.setState({
  //             visible: false,
  //             loading: false,
  //           }, () => {
  //             message.success('新增用户成功')
  //             this.props.closeCallBack && this.props.closeCallBack()
  //           })
  //         },
  //         (error) => {
  //           console.log(error)
  //           this.setState({ loading: false })
  //         },
  //       )
  //     }
  //   })
  // }

  getTitleStr = () => {
    const { isEdit, isCheck } = this.props
    if (isEdit) {
      return '编辑用户'
    } if (isCheck) {
      return '查看用户'
    }
    return '新增用户'
  }

  // 编辑模式打开窗口
  // eslint-disable-next-line react/no-unused-class-component-methods
  openEditModal(data) {
    this.setState({
      visible: true,
      id: data.id,
    }, () => {
      this.setValue(data)
    })
  }

  render() {
    const {
      visible, roleOptions, loading, listUserSecret,
    } = this.state
    const {
      isEdit, isCheck, user,
    } = this.props
    const { isAuth } = user
    const emailReg = regExp.email()
    const phoneReg = regExp.phone()
    const nameReg = regExp.name()
    const passwordReg = regExp.password(8, 32)
    return (
      <Modal
        title={this.getTitleStr()}
        visible={visible}
        width={520}
        onCancel={this.closeModal}
        maskClosable={false}
        onOk={this.onConfirm}
        footer={
          isCheck ? null : (
            <>
              <Button
                onClick={this.closeModal}
              >
                取消
              </Button>
              <Button
                onClick={this.onConfirm}
                type="primary"
                loading={loading}
              >
                确定
              </Button>
            </>
          )
        }
        bodyStyle={{
          height: `${(document.documentElement.clientHeight * 0.65) > 552 ? 552 : (document.documentElement.clientHeight * 0.65)}px`,
          overflowY: 'auto',
        }}
      >
        <Form
          ref={this.form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={{
            abled: true,
          }}
          autoComplete="off"
        >
          <Item
            label="账号"
            name="id"
            rules={[
              { required: true, message: '请输入账号' },
              {
                pattern: new RegExp(nameReg.reg, 'g'),
                message: nameReg.text,
              },
            ]}
          >
            <Input
              disabled={isEdit || isCheck}
              placeholder="请输入账号"
            />
          </Item>
          {
            !isEdit && !isCheck && (
              <>
                <Item
                  label="登录密码"
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    {
                      pattern: new RegExp(passwordReg.reg, 'g'),
                      message: passwordReg.text,
                    },
                  ]}
                >
                  <Input.Password
                    autoComplete="new-password"
                    placeholder="请输入密码"
                  />
                </Item>
                <Item
                  label="确认密码"
                  name="confirm"
                  dependencies={['password']}
                  rules={
                    [
                      {
                        required: true, message: '请再次输入密码',
                      },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('password') === value) {
                            return Promise.resolve()
                          }
                          return Promise.reject(new Error('两次输入的密码不相同'))
                        },
                      }),
                    ]
                  }
                >
                  <Input.Password
                    autoComplete="new-password"
                    placeholder="请再次输入密码"
                  />
                </Item>
              </>
            )
          }
          <Item
            label="姓名"
            name="name"
            rules={[
              // { required: true, message: '请输入姓名' },
              {
                pattern: new RegExp(nameReg.reg, 'g'),
                message: nameReg.text,
              },
            ]}
          >
            <Input
              disabled={isCheck}
              placeholder="请输入姓名"
            />
          </Item>
          <Item
            label="手机号"
            name="phone"
            rules={[
              // { required: true, message: '请输入手机号' },
              {
                pattern: new RegExp(phoneReg.reg, 'g'),
                message: phoneReg.text,
              },
            ]}
          >
            <Input
              disabled={isCheck}
              placeholder="请输入手机号"
            />
          </Item>
          <Item
            label="邮箱"
            name="email"
            rules={[
              // { required: true, message: '请输入邮箱' },
              {
                pattern: new RegExp(emailReg.reg, 'g'),
                message: emailReg.text,
              },
            ]}
          >
            <Input
              disabled={isCheck}
              placeholder="请输入邮箱"
            />
          </Item>
          {/* <Item
            label="角色"
            name="roleId"
            rules={[{ required: !!((isAuth == 1 || isAuth == 3)), message: '请选择角色' }]}
          >
            <Select
              disabled={isCheck || isAuth == 2}
              placeholder="请选择角色"
              showSearch
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {
                roleOptions.map((item, index) => (
                  <Option
                    value={item.value}
                    key={index}
                  >
                    {item.title}
                  </Option>
                ))
              }
            </Select>
          </Item> */}
          {/* {
            (isAuth != 2 || isCheck) && (
              <Item
                label="人员密级"
                name="securityLevelId"
                rules={[{ required: true, message: '请选择人员密级' }]}
              >
                <Select
                  disabled={isCheck || isAuth == 2}
                  placeholder="请选择人员密级"
                  showSearch
                  filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {
                    listUserSecret && listUserSecret.map((item, index) => (
                      <Option
                        value={item.id}
                        key={index}
                      >
                        {item.secretName}
                      </Option>
                    ))
                  }
                </Select>
              </Item>
            )
          } */}
          {/* <Item
            label="部门"
            name="dept"
          >
            <Input
              disabled={isCheck}
              placeholder="请输入部门"
            />
          </Item>
          <Item
            label="职位"
            name="title"
          >
            <Input
              disabled={isCheck}
              placeholder="请输入职位"
            />
          </Item> */}
          {/* {
            isCheck && (
              <Item
                label="是否启用"
                name="rowState"
              >
                <Input
                  disabled={isCheck}
                />
              </Item>)
          } */}
        </Form>
      </Modal>
    )
  }
}
